import sys
import os

try:
    from osgeo import ogr
except:
    import ogr


def __GetName(filename):
    return os.path.basename(filename).split(".")[0]


def __GetFieldTypeName(layer):
    layer_defin = layer.GetLayerDefn()
    field_defin_dict = {}
    """:type : osgeo.ogr.FeatureDefn"""
    for i in range(layer_defin.GetFieldCount()):
        field_defn = layer_defin.GetFieldDefn(i)
        """:type : osgeo.ogr.FieldDefn"""
        field_name = field_defn.GetName()
        field_type_name = field_defn.GetTypeName()
        field_defin_dict[field_name] = field_type_name
    return field_defin_dict


def __GetFieldValue(layer):
    list = []
    for i in range(layer.GetFeatureCount()):
        feat = layer.GetFeature(i)
        """:type : osgeo.ogr.Feature"""
        field_value_dict = {}
        for j in range(feat.GetFieldCount()):
            field_value = feat.GetField(j)
            field_name = layer.GetLayerDefn().GetFieldDefn(j).GetName()
            field_value_dict[field_name] = field_value
            field_value_dict["geom"] = __POLYGON2MULTIPOLYGON(feat.GetGeometryRef().ExportToWkt())
        list.append(field_value_dict)
    return list


def __POLYGON2MULTIPOLYGON(polygon):
    if polygon.startswith("POLYGON"):
        polygon = 'MULTIPOLYGON(' + polygon[8:]
        polygon += ")"
    return polygon


def Read_shp(filename):
    if filename is None or filename == "":
        return None
    driver = ogr.GetDriverByName('ESRI Shapefile')
    print(filename)
    dataSource = driver.Open(filename, 0)
    """:type : osgeo.ogr.DataSource"""
    if dataSource is None:
        print('could not open')
        sys.exit(1)
    layer = dataSource.GetLayer()
    """:type : osgeo.ogr.Layer"""
    print("filename:", filename)
    return __GetName(filename), __GetFieldTypeName(layer), __GetFieldValue(layer)


def main():
    filename = 'shpdata/bou2_4p.shp'
    name, field_type_name, field_value = Read_shp(filename)
    print(name)
    print(field_type_name)
    print(field_value)


if __name__ == '__main__':
    main()
